import { app, BrowserWindow, Menu, Tray, ipcMain, dialog, shell, nativeTheme } from 'electron'
import path from 'path'
import { promises as fs } from 'fs'
import { fileURLToPath } from 'url'
import pkg from 'electron-updater'
const { autoUpdater } = pkg
// 获取当前文件的目录路径（ES模块中__dirname不可用）
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

let mainWindow
let splashWindow
let tray = null

// 应用配置
const APP_CONFIG = {
  minWidth: 1000,
  minHeight: 700,
  defaultWidth: 1400,
  defaultHeight: 900,
  enableTray: true,
  minimizeToTray: true,
  startMinimized: false
}

function createSplashWindow() {
  splashWindow = new BrowserWindow({
    width: 400,
    height: 300,
    frame: false,
    alwaysOnTop: true,
    transparent: true,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true
    }
  })

  splashWindow.loadFile(path.join(__dirname, 'splash.html'))
  
  splashWindow.on('closed', () => {
    splashWindow = null
  })
}

function createWindow() {
  // 创建启动画面
  createSplashWindow()

  mainWindow = new BrowserWindow({
    width: APP_CONFIG.defaultWidth,
    height: APP_CONFIG.defaultHeight,
    minWidth: APP_CONFIG.minWidth,
    minHeight: APP_CONFIG.minHeight,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
      preload: path.join(__dirname, 'preload.js'),
      webSecurity: true,
      allowRunningInsecureContent: false
    },
    icon: getAppIcon(),
    show: false,
    titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default',
    backgroundColor: nativeTheme.shouldUseDarkColors ? '#1a1a1a' : '#ffffff'
  })

  // 开发环境加载开发服务器，生产环境加载构建文件
  const isDev = process.env.NODE_ENV === 'development'
  if (isDev) {
    mainWindow.loadURL('http://localhost:5173') // Vite默认端口
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  mainWindow.once('ready-to-show', () => {
    if (splashWindow) {
      splashWindow.close()
    }
    mainWindow.show()
    
    // 检查更新
    if (!isDev) {
      autoUpdater.checkForUpdatesAndNotify()
    }
  })

  mainWindow.on('close', (event) => {
    if (APP_CONFIG.minimizeToTray && !app.isQuiting) {
      event.preventDefault()
      mainWindow.hide()
      
      // 首次最小化到托盘时显示提示
      if (!app.hasShownTrayNotification) {
        tray?.displayBalloon({
          iconType: 'info',
          title: 'File History Manager',
          content: '应用已最小化到系统托盘，双击托盘图标可重新打开'
        })
        app.hasShownTrayNotification = true
      }
    }
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  // 处理外部链接
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    shell.openExternal(url)
    return { action: 'deny' }
  })

  // 防止导航到外部URL
  mainWindow.webContents.on('will-navigate', (event, navigationUrl) => {
    const parsedUrl = new URL(navigationUrl)
    
    if (parsedUrl.origin !== 'http://localhost:5173' && parsedUrl.origin !== 'file://') {
      event.preventDefault()
    }
  })
}

function getAppIcon() {
  const iconPath = path.join(__dirname, '../public')
  if (process.platform === 'win32') {
    return path.join(iconPath, 'icon.ico')
  } else if (process.platform === 'darwin') {
    return path.join(iconPath, 'icon.icns')
  } else {
    return path.join(iconPath, 'icon.png')
  }
}

function createTray() {
  if (!APP_CONFIG.enableTray) return

  const iconPath = process.platform === 'win32' 
    ? path.join(__dirname, '../public/icon.ico')
    : path.join(__dirname, '../public/icon.png')
  
  tray = new Tray(iconPath)
  
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示主窗口',
      click: () => {
        if (mainWindow) {
          if (mainWindow.isMinimized()) mainWindow.restore()
          mainWindow.show()
          mainWindow.focus()
        } else {
          createWindow()
        }
      }
    },
    {
      label: '打开History目录',
      click: async () => {
        const result = await dialog.showOpenDialog({
          properties: ['openDirectory'],
          title: '选择History目录'
        })
        
        if (!result.canceled && result.filePaths.length > 0) {
          if (mainWindow) {
            mainWindow.webContents.send('open-history-directory', result.filePaths[0])
            if (mainWindow.isMinimized()) mainWindow.restore()
            mainWindow.show()
            mainWindow.focus()
          }
        }
      }
    },
    { type: 'separator' },
    {
      label: '设置',
      click: () => {
        if (mainWindow) {
          mainWindow.webContents.send('open-settings')
          if (mainWindow.isMinimized()) mainWindow.restore()
          mainWindow.show()
          mainWindow.focus()
        }
      }
    },
    {
      label: '关于',
      click: () => {
        if (mainWindow) {
          mainWindow.webContents.send('show-about')
          if (mainWindow.isMinimized()) mainWindow.restore()
          mainWindow.show()
          mainWindow.focus()
        }
      }
    },
    { type: 'separator' },
    {
      label: '退出',
      click: () => {
        app.isQuiting = true
        app.quit()
      }
    }
  ])
  
  tray.setToolTip('File History Manager')
  tray.setContextMenu(contextMenu)
  
  // 双击托盘图标显示/隐藏窗口
  tray.on('double-click', () => {
    if (mainWindow) {
      if (mainWindow.isVisible()) {
        mainWindow.hide()
      } else {
        mainWindow.show()
        mainWindow.focus()
      }
    } else {
      createWindow()
    }
  })
}

// 创建应用菜单
function createMenu() {
  const isMac = process.platform === 'darwin'
  
  const template = [
    // macOS 应用菜单
    ...(isMac ? [{
      label: app.getName(),
      submenu: [
        { label: '关于 ' + app.getName(), role: 'about' },
        { type: 'separator' },
        { label: '服务', role: 'services' },
        { type: 'separator' },
        { label: '隐藏 ' + app.getName(), accelerator: 'Command+H', role: 'hide' },
        { label: '隐藏其他', accelerator: 'Command+Shift+H', role: 'hideothers' },
        { label: '显示全部', role: 'unhide' },
        { type: 'separator' },
        { label: '退出', accelerator: 'Command+Q', role: 'quit' }
      ]
    }] : []),
    
    // 文件菜单
    {
      label: '文件',
      submenu: [
        {
          label: '打开History目录',
          accelerator: 'CmdOrCtrl+O',
          click: async () => {
            const result = await dialog.showOpenDialog(mainWindow, {
              properties: ['openDirectory'],
              title: '选择History目录'
            })
            
            if (!result.canceled && result.filePaths.length > 0) {
              mainWindow.webContents.send('open-history-directory', result.filePaths[0])
            }
          },
        },
        {
          label: '导出搜索结果',
          accelerator: 'CmdOrCtrl+E',
          click: () => {
            mainWindow.webContents.send('export-search-results')
          },
        },
        { type: 'separator' },
        {
          label: '设置',
          accelerator: 'CmdOrCtrl+,',
          click: () => {
            mainWindow.webContents.send('open-settings')
          },
        },
        { type: 'separator' },
        ...(!isMac ? [{
          label: '退出',
          accelerator: 'Ctrl+Q',
          click: () => {
            app.quit()
          },
        }] : []),
      ],
    },
    
    // 编辑菜单
    {
      label: '编辑',
      submenu: [
        { label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
        { label: '重做', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
        { type: 'separator' },
        { label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
        { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
        { label: '全选', accelerator: 'CmdOrCtrl+A', role: 'selectall' }
      ],
    },
    
    // 搜索菜单
    {
      label: '搜索',
      submenu: [
        {
          label: '搜索文件',
          accelerator: 'CmdOrCtrl+F',
          click: () => {
            mainWindow.webContents.send('focus-search')
          },
        },
        {
          label: '高级搜索',
          accelerator: 'CmdOrCtrl+Shift+F',
          click: () => {
            mainWindow.webContents.send('open-advanced-search')
          },
        },
        { type: 'separator' },
        {
          label: '清空搜索历史',
          click: () => {
            mainWindow.webContents.send('clear-search-history')
          },
        },
      ],
    },
    
    // 视图菜单
    {
      label: '视图',
      submenu: [
        { label: '重新加载', accelerator: 'CmdOrCtrl+R', role: 'reload' },
        { label: '强制重新加载', accelerator: 'CmdOrCtrl+Shift+R', role: 'forceReload' },
        { label: '开发者工具', accelerator: 'F12', role: 'toggleDevTools' },
        { type: 'separator' },
        { label: '实际大小', accelerator: 'CmdOrCtrl+0', role: 'resetZoom' },
        { label: '放大', accelerator: 'CmdOrCtrl+Plus', role: 'zoomIn' },
        { label: '缩小', accelerator: 'CmdOrCtrl+-', role: 'zoomOut' },
        { type: 'separator' },
        { label: '全屏', accelerator: 'F11', role: 'togglefullscreen' },
        { type: 'separator' },
        {
          label: '切换主题',
          accelerator: 'CmdOrCtrl+T',
          click: () => {
            mainWindow.webContents.send('toggle-theme')
          },
        },
      ],
    },
    
    // 工具菜单
    {
      label: '工具',
      submenu: [
        {
          label: '性能监控',
          accelerator: 'CmdOrCtrl+Shift+P',
          click: () => {
            mainWindow.webContents.send('open-performance-monitor')
          },
        },
        {
          label: '清空缓存',
          click: () => {
            mainWindow.webContents.send('clear-cache')
          },
        },
        { type: 'separator' },
        {
          label: '检查更新',
          click: () => {
            autoUpdater.checkForUpdatesAndNotify()
          },
        },
      ],
    },
    
    // 窗口菜单 (macOS)
    ...(isMac ? [{
      label: '窗口',
      submenu: [
        { label: '关闭', accelerator: 'CmdOrCtrl+W', role: 'close' },
        { label: '最小化', accelerator: 'CmdOrCtrl+M', role: 'minimize' },
        { label: '缩放', role: 'zoom' },
        { type: 'separator' },
        { label: '前置所有窗口', role: 'front' }
      ]
    }] : []),
    
    // 帮助菜单
    {
      label: '帮助',
      submenu: [
        {
          label: '用户指南',
          click: () => {
            shell.openExternal('https://github.com/your-repo/file-history-manager/wiki')
          },
        },
        {
          label: '快捷键',
          accelerator: 'CmdOrCtrl+?',
          click: () => {
            mainWindow.webContents.send('show-shortcuts')
          },
        },
        { type: 'separator' },
        {
          label: '报告问题',
          click: () => {
            shell.openExternal('https://github.com/your-repo/file-history-manager/issues')
          },
        },
        ...(!isMac ? [{ type: 'separator' }, {
          label: '关于',
          click: () => {
            mainWindow.webContents.send('show-about')
          },
        }] : []),
      ],
    },
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

// IPC 处理程序
ipcMain.handle('read-file', async (event, filePath) => {
  try {
    // 安全检查：确保文件路径在允许的范围内
    if (!isPathSafe(filePath)) {
      throw new Error('Access denied: Invalid file path')
    }
    
    const content = await fs.readFile(filePath, 'utf-8')
    const stats = await fs.stat(filePath)
    
    return { 
      success: true, 
      content,
      size: stats.size,
      mtime: stats.mtime,
      ctime: stats.ctime
    }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('write-file', async (event, filePath, content) => {
  try {
    if (!isPathSafe(filePath)) {
      throw new Error('Access denied: Invalid file path')
    }
    
    // 确保目录存在
    await fs.mkdir(path.dirname(filePath), { recursive: true })
    await fs.writeFile(filePath, content, 'utf-8')
    
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('read-directory', async (event, dirPath) => {
  try {
    if (!isPathSafe(dirPath)) {
      throw new Error('Access denied: Invalid directory path')
    }
    
    const files = await fs.readdir(dirPath, { withFileTypes: true })
    const result = await Promise.all(
      files.map(async (file) => {
        const fullPath = path.join(dirPath, file.name)
        let stats = null
        
        try {
          stats = await fs.stat(fullPath)
        } catch (error) {
          // 忽略无法访问的文件
        }
        
        return {
          name: file.name,
          isDirectory: file.isDirectory(),
          path: fullPath,
          size: stats?.size || 0,
          mtime: stats?.mtime || null,
          ctime: stats?.ctime || null
        }
      })
    )
    
    return { success: true, files: result }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('copy-file', async (event, sourcePath, targetPath) => {
  try {
    if (!isPathSafe(sourcePath) || !isPathSafe(targetPath)) {
      throw new Error('Access denied: Invalid file path')
    }
    
    await fs.mkdir(path.dirname(targetPath), { recursive: true })
    await fs.copyFile(sourcePath, targetPath)
    
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('show-save-dialog', async (event, options) => {
  try {
    const result = await dialog.showSaveDialog(mainWindow, options)
    return result
  } catch (error) {
    return { canceled: true, error: error.message }
  }
})

ipcMain.handle('show-open-dialog', async (event, options) => {
  try {
    const result = await dialog.showOpenDialog(mainWindow, options)
    return result
  } catch (error) {
    return { canceled: true, error: error.message }
  }
})

ipcMain.handle('show-message-box', async (event, options) => {
  try {
    const result = await dialog.showMessageBox(mainWindow, options)
    return result
  } catch (error) {
    return { response: 0, error: error.message }
  }
})

ipcMain.handle('get-app-version', () => {
  return app.getVersion()
})

ipcMain.handle('get-app-path', (event, name) => {
  return app.getPath(name)
})

ipcMain.handle('open-external', async (event, url) => {
  try {
    await shell.openExternal(url)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 安全检查函数
function isPathSafe(filePath) {
  // 基本的路径安全检查
  const normalizedPath = path.normalize(filePath)
  
  // 禁止访问系统敏感目录
  const forbiddenPaths = [
    '/etc',
    '/sys',
    '/proc',
    'C:\\Windows\\System32',
    'C:\\Program Files'
  ]
  
  return !forbiddenPaths.some(forbidden => 
    normalizedPath.toLowerCase().startsWith(forbidden.toLowerCase())
  )
}

// 自动更新配置
autoUpdater.on('checking-for-update', () => {
  console.log('Checking for update...')
})

autoUpdater.on('update-available', (info) => {
  console.log('Update available.')
  mainWindow?.webContents.send('update-available', info)
})

autoUpdater.on('update-not-available', (info) => {
  console.log('Update not available.')
})

autoUpdater.on('error', (err) => {
  console.log('Error in auto-updater. ' + err)
})

autoUpdater.on('download-progress', (progressObj) => {
  let log_message = "Download speed: " + progressObj.bytesPerSecond
  log_message = log_message + ' - Downloaded ' + progressObj.percent + '%'
  log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')'
  console.log(log_message)
  mainWindow?.webContents.send('download-progress', progressObj)
})

autoUpdater.on('update-downloaded', (info) => {
  console.log('Update downloaded')
  mainWindow?.webContents.send('update-downloaded', info)
})

// 应用事件处理
app.whenReady().then(() => {
  // 设置应用用户模型ID (Windows)
  if (process.platform === 'win32') {
    app.setAppUserModelId('com.filehistory.manager')
  }
  
  createWindow()
  createMenu()
  createTray()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  // 如果启用了托盘且不是macOS，不要退出应用
  if (process.platform !== 'darwin' && !APP_CONFIG.enableTray) {
    app.quit()
  }
})

app.on('before-quit', (event) => {
  app.isQuiting = true
  
  // 清理资源
  if (mainWindow) {
    mainWindow.webContents.send('app-before-quit')
  }
  
  // 清理托盘
  if (tray) {
    tray.destroy()
    tray = null
  }
})

app.on('will-quit', (event) => {
  // 最后的清理机会
  console.log('Application will quit')
})

// 处理协议 (用于深度链接)
app.setAsDefaultProtocolClient('file-history-manager')

// 处理第二个实例
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时，聚焦到主窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })
}

// 安全设置
app.on('web-contents-created', (event, contents) => {
  contents.on('new-window', (event, navigationUrl) => {
    event.preventDefault()
    shell.openExternal(navigationUrl)
  })
  
  contents.on('will-attach-webview', (event, webPreferences, params) => {
    // 禁用 webview
    event.preventDefault()
  })
  
  contents.on('will-navigate', (event, navigationUrl) => {
    const parsedUrl = new URL(navigationUrl)
    
    if (parsedUrl.origin !== 'http://localhost:5173' && parsedUrl.origin !== 'file://') {
      event.preventDefault()
    }
  })
})